import { Component, OnInit, Input,ViewChild,ElementRef ,ViewEncapsulation} from '@angular/core';
import {BAR_MAP,renderThumbStyle} from '../util'
@Component({
  selector: 'el-bar',
  template: `
  <div #self class="el-scrollbar__bar {{keyClass}}" (mousedown)=" this.clickTrackHandler()"  >
    <div #thumb
      class="el-scrollbar__thumb"
      (mousedown)="this.clickThumbHandler()">
    </div>
  </div>
  `,
  styleUrls: ['./el-bar.component.css'],
  encapsulation:ViewEncapsulation.None
})
export class ElBarComponent implements OnInit {
  
  // prop
  @Input() vertical:boolean;
  @Input() size:string;
  @Input() move:number;

  // state
  cursorDown:boolean
  @ViewChild('thumb') thumb:ElementRef;
  @ViewChild('self') self:ElementRef
  
  bar:any;
  wrap:any;

  // methods
  clickThumbHandler(e){
    this.startDrag(e);
    this[this.bar.axis] = (e.currentTarget[this.bar.offset] - (e[this.bar.client] - e.currentTarget.getBoundingClientRect()[this.bar.direction]));
  }

  clickTrackHandler(e) {
    const offset = Math.abs(e.target.getBoundingClientRect()[this.bar.direction] - e[this.bar.client]);
    const thumbHalf = (this.thumb.nativeElement[this.bar.offset] / 2);
    const thumbPositionPercentage = ((offset - thumbHalf) * 100 / this.self.nativeElement[this.bar.offset]);

    this.wrap[this.bar.scroll] = (thumbPositionPercentage * this.wrap[this.bar.scrollSize] / 100);
  }

  constructor() { }

  ngOnInit() {
      this.bar=BAR_MAP[this.vertical?'vertical':'horizontal'];
      const style=renderThumbStyle({size:this.size,move:this.move,bar:this.bar});
      this.thumb.nativeElement.style=style
  }
  startDrag(e) {
      e.stopImmediatePropagation();
      this.cursorDown = true;

      document.onmousemove=(e)=>{
          this.mouseMoveDocumentHandler(e)
      };
      document.onmouseup=e=>{
          this.mouseUpDocumentHandler(e)
      }
  
      document.onselectstart = () => false;
  }

  mouseMoveDocumentHandler(e) {
    if (this.cursorDown === false) {return};
    const prevPage = this[this.bar.axis];

    if (!prevPage) {return};

    const offset = ((this.self.nativeElement.getBoundingClientRect()[this.bar.direction] - e[this.bar.client]) * -1);
    const thumbClickPosition = (this.self.nativeElement.thumb[this.bar.offset] - prevPage);
    const thumbPositionPercentage = ((offset - thumbClickPosition) * 100 / this.self.nativeElement[this.bar.offset]);

    this.wrap[this.bar.scroll] = (thumbPositionPercentage * this.wrap[this.bar.scrollSize] / 100);
  }

  mouseUpDocumentHandler(e) {
      this.cursorDown = false;
      this[this.bar.axis] = 0;
      document.onmousemove=null;
      
      document.onselectstart = null;
  }



}
